<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Target
 *
 * @name		Controller Target
 * @author		Rizki Anurka
 * 
 */
 
 class Target extends CI_Controller{
    /**
     * Target::Target()
     * 
     * @return
     */
    function Target(){            
        parent::__construct();
        $this->load->library('session');
        $this->load->model('mglobal');        
       	$this->load->model('mmaster');        
       	$this->load->model('mkpi');
        $this->load->model('musers');
        $this->load->helper('url');
        $this->load->helper('captcha');
        $this->load->model('mtarget');
        
        $login_status=$this->session->userdata('is_logged_in');
        if(!isset($login_status) || $login_status == 0){
            redirect(base_url() .'index.php/login');
        }
    }
    
    /**
     * Target::index()
     * 
     * @return
     */
    function index(){
        redirect(base_url() .'index.php/target/assignment');
    }
    
	function approve($proses="",$id=""){
		$data['template']="shell/smooth"; $data;
        $data['data']=array("nik"=>"");
        $data['main_view']      = 'f-target-approve';
        if ($proses=="approve"){
            if($id!=""){
				$this->mkpi->updateApproval($id,1); 
			 }
        } elseif($proses=="reject"){ 
            if ($id!=""){
				$this->mkpi->updateApproval($id,-1); 
            }
        } elseif($proses=="update"){ 
            if (isset($_POST['target_id'])){
                $newdata['kpi_target']=$_POST['kpi_target'];
                $newdata['updated_on']=date("Y-m-d H:i:s");
                $newdata['updated_by']=$this->session->userdata('username');
				$newdata['istatus']=100;
                $this->mkpi->updateTarget($_POST['target_id'],$newdata); 	
                redirect(base_url() .'index.php/target/approve');
            } else {
                $targetData=$this->mkpi->getTargetById($id);
                foreach($targetData as $row){
                    $data['data']['nik']=$row->nik;
                    $data['data']['kpi_code']=$row->kpi_code;
                    $data['data']['target_id']=$row->target_id;
                    $data['data']['kpi_description']=$row->kpi_description;
                    $data['data']['kpi_target']=$row->kpi_target;
                    $data['data']['user_name']=$row->user_name;
					$data['data']['allocated']=$this->mkpi->getAllocatedKPI($id);
                }
            }
        } 
		//$data['data']['period']=$this->mkpi->getDefaultPeriod();
        $this->load->view($data['template'],$data);
	}
	
    /**
     * Target::assign()
     * 
     * @param string $proses
     * @param string $id
     * @return
     */
    function assign($proses="",$id=""){        
        $data['template']="shell/smooth"; $data;
        $data['data']=array("nik"=>"");
        $data['main_view']      = 'f-target-assign';
        if ($proses=="new"){
            if(isset($_POST['nik'])){
                $datakpi['kpi']=$_POST;
                $datakpi['nik']=$_POST['nik'];
				$periode=$_POST['period'];
				$startmonth=$_POST['start'];
				unset($datakpi['kpi']['period']);
                unset($datakpi['kpi']['nik']);
                unset($datakpi['kpi']['submit']);            
                unset($datakpi['kpi']['lblname2']);   
				unset($datakpi['kpi']['start']);
                $i=0;
                $user=$this->musers->getById($this->session->userdata('username'));
                $cluster=$this->mkpi->getCluster();
                foreach($datakpi['kpi'] as $k=>$v){
                    $datacooked[$i]['nik']=$datakpi['nik'];
                    $datacooked[$i]['kpi_code']=$k;
                    if($v>0){
                        $datacooked[$i]['kpi_target']=$v;
                    } else {
                        $datacooked[$i]['kpi_target']="0";
                    }
                    //$datacooked[$i]['kpi_month']=date('Ym');
                    $datacooked[$i]['created_by']=$this->session->userdata('username');                    
                    $datacooked[$i]['territory_id']=$cluster;
                    $i++;
                } 
				$m=substr($startmonth,-2);
				$y=substr($startmonth,0,4);
				for ($i=0;$i<$periode;$i++){
					
					foreach($datacooked as $key=>$value)
						$datacooked[$key]['kpi_month']=$y.$m;
					$this->mkpi->setTarget($datacooked);
					if($m==12){
						$m="01";
						$y=$y+1;
					} else {
						$m=$m+1;
						if($m<10)
							$m="0".$m;
					}
				}
			}
        } elseif($proses=="update"){ 
            if (isset($_POST['target_id'])){
                $newdata['kpi_target']=$_POST['kpi_target'];
                $newdata['updated_on']=date("Y-m-d H:i:s");
                $newdata['updated_by']=$this->session->userdata('username');
                $this->mkpi->updateTarget($_POST['target_id'],$newdata);                
                redirect(base_url() .'index.php/target/assign');
            } else {
                $targetData=$this->mkpi->getTargetById($id);
                foreach($targetData as $row){
                    $data['data']['nik']=$row->nik;
                    $data['data']['kpi_code']=$row->kpi_code;
                    $data['data']['target_id']=$row->target_id;
                    $data['data']['kpi_description']=$row->kpi_description;
                    $data['data']['kpi_target']=$row->kpi_target;
                    $data['data']['user_name']=$row->user_name;
					$data['data']['allocated']=$this->mkpi->getAllocatedKPI($id);
                }
            }
        } elseif($proses=="delete"){
            if($id!=""){
                $this->mkpi->deleteTarget($id);
            }
        }
		$data['data']['period']=$this->mkpi->getDefaultPeriod();
        $this->load->view($data['template'],$data);
    }
    function allocate($proses="",$id=""){
        $data['template']="shell/smooth";
        $data['data']=array("region"=>"","regionid"=>"");
        $data['main_view'] = 'f-target-allocate';       

		 if ($proses=="new"){
            if(isset($_POST['nik'])){
                $dataAllocation['allocation']=$_POST;
                $dataAllocation['nik']=$_POST['nik'];
				$periode=$_POST['period'];
				$startmonth=$_POST['start'];
				unset($dataAllocation['allocation']['period']);
                unset($dataAllocation['allocation']['nik']);
                unset($dataAllocation['allocation']['submit']);            
                unset($dataAllocation['allocation']['region']); 
				unset($dataAllocation['allocation']['regionid']);
				unset($dataAllocation['allocation']['cluster']);				
				unset($dataAllocation['allocation']['start']);
                $i=0;
                //$user=$this->musers->getById($this->session->userdata('username'));
                //$cluster=$this->mkpi->getCluster();
                foreach($dataAllocation['allocation'] as $k=>$v){
                    $datacooked[$i]['nik']=$dataAllocation['nik'];
                    $datacooked[$i]['kpi_code']=$k;
                    if($v>0){
                        $datacooked[$i]['target']=$v;
                    } else {
                        $datacooked[$i]['target']="0";
                    }
                    $datacooked[$i]['created_by']=$this->session->userdata('username');  
					
                    //$datacooked[$i]['territory_id']=$cluster;
                    $i++;
                } 
				$m=substr($startmonth,-2);
				$y=substr($startmonth,0,4);
				for ($i=0;$i<$periode;$i++){
					
					foreach($datacooked as $key=>$value)
						$datacooked[$key]['allocated_month']=$y.$m;
					$this->mkpi->setAllocation($datacooked);
					if($m==12){
						$m="01";
						$y=$y+1;
					} else {
						$m=$m+1;
						if($m<10)
							$m="0".$m;
					}
				}
			} 			
        } elseif($proses=="update"){ 
            if (isset($_POST['allocation_id'])){
                $newdata['target']=$_POST['target'];
                $newdata['updated_on']=date("Y-m-d H:i:s");
                $newdata['updated_by']=$this->session->userdata('username');
                $this->mkpi->updateAllocation($_POST['allocation_id'],$newdata);                
                redirect(base_url() .'index.php/target/allocate');
            } else {
                $targetData=$this->mkpi->getAllocationById($id);
                foreach($targetData as $row){
                    $data['data']['allocation_id']=$row->allocation_id;
                    $data['data']['nik']=$row->nik;
					$data['data']['user_name']=$row->user_name;
                    $data['data']['kpi_code']=$row->kpi_code;					
                    $data['data']['kpi_description']=$row->kpi_description;
                    $data['data']['target']=$row->target;                    
                    $data['data']['allocated_month']=$row->allocated_month;
                }
            }
        }
		
		$data['data']['period']=$this->mkpi->getDefaultPeriod();		
        $this->load->view($data['template'],$data);
    }
    
    
    /**
     * Target::assigned_read()
     * 
     * @return
     */
    function assigned_read(){        
        echo json_encode( $this->mkpi->getTarget() );
    }
	
	 function unapproved_read(){        
        echo json_encode( $this->mkpi->getUnapproved() );
    }
        
    /**
     * Target::kpi_read()
     * 
     * @param string $usr_group
     * @return
     */
    function kpi_read($month="",$year="",$usr_group=""){       
            echo json_encode ($this->mkpi->getKPIByUserGroup($usr_group,$month,$year));         
    }
    
    /**
     * Target::downline_read()
     * 
     * @return
     */
    function downline_read(){
        $keyword = $this->input->post('term');
        $result=$this->mkpi->getDownline($keyword);
        if(count($result)){
            $data['respond']=true;
            $data['result']['count']=count($result);
            $data['result']['data']=$result;
        }else{
            $data['respond']=false;
        }
        echo json_encode($result);
    }
	
	function territory_read($type="",$parent=""){
	
        $keyword = $this->input->post('term');
		$result=$this->mkpi->getTerritoryName($type,$keyword,$parent);
		echo json_encode($result);
	}
	
	function cc_read(){
		$keyword=$this->input->post('term');
		$result=$this->mkpi->getAllClusterCoordinator($keyword);
		echo json_encode($result);
	}
	
	function allocated_read(){
		$result=$this->mkpi->getAllocatedTarget();
		echo json_encode($result);
	}
    /**
     * Target::kpi_map()
     * 
     * @param string $proses
     * @param string $id
     * @return
     */
    function kpi_map($proses="", $id=""){
        $data['template']="shell/smooth";
        $data['data']=array("kpi_code"=>"","kpi_description"=>"","remark"=>"","user_group_id"=>"","user_group_list"=>"");
        $data['main_view']= "f-kpi-map";       
            
        if ($proses=="new"){           
            if(isset($_POST['kpi_code'])){
                $datakpi['kpi_code']=$_POST['kpi_code'];
                $datakpi['kpi_description']=$_POST['kpi_description'];
                $datakpi['remark']=$_POST['remark'];
                $datakpi['user_group_id']=$_POST['user_group_id'];
				$datakpi['kpi_parent']=$_POST['kpi_parent_combo'];
                $this->mkpi->setKpi($datakpi);                
            }
            $data['data']['user_group_list']=$this->mkpi->getAllUserGroup();
        } elseif ($proses=="update" ){            
            if(isset($_POST['kpi_code'])){
                $newdata['kpi_description']=$_POST['kpi_description'];
                $newdata['remark']=$_POST['remark'];
                $newdata['user_group_id']=$_POST['user_group_id'];				
				$newdata['kpi_parent']=$_POST['kpi_parent_combo'];
                $this->mkpi->updateKPI($_POST['kpi_code'],$newdata);
            } else {
                $data['data']['kpi_code']=$id;
                $datakpi=$this->mkpi->getKPIByKPICode($id);
                $data['data']=$datakpi;
            }
            $data['data']['user_group_list']=$this->mkpi->getAllUserGroup();
        } elseif($proses=="delete"){
            if($id!=""){
                $this->mkpi->deleteKPI($id);
            }
        }        
       // $data['data']['user_group_list']=$this->mkpi->getAllUserGroup();
        $this->load->view($data['template'],$data);
    }
	
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    function assignNew($data){	  
	   $this->mtarget->setTarget($data);
	}

    function approval($process="",$kpi_code="",$month=""){  
        $data['template']="shell/smooth";
        $data['main_view']      = 'f-target-approve';
        $data['data']['unapprovedTarget']=$this->mtarget->getTargetUnapprove($kpi_code,$month);
        if($_POST)
        {
            $temp=$_POST;
            unset($temp['submit']);
            foreach($temp as $key=>$val){
                $dataInput[]=array('target_id'=>$key,'kpi_target'=>$val,'istatus'=>1,'updated_by'=>$this->session->userdata('username'));    
            }            
            //print_r($data);
            $this->mtarget->approveTarget($dataInput);
         
        }
        $this->load->view($data['template'],$data);
        
    }

	function assignment($process="", $id=""){
        $data['template']="shell/smooth"; 
        $data['main_view']      = 'temp/f-target';
        if ($process==""){
            if($_POST){
                $datas=$_POST;
                $month=$_POST['month'];
                $action=$_POST['submit'];
                unset($datas['month']);
                unset($datas['user_group']);
                unset($datas['submit']);
      
               $i=0;
                foreach($datas as $key=>$value){
                    $temp=explode('-',$key);   
                    $dataInput[$i]['kpi_code']=$temp[0];
                    $dataInput[$i]['nik']=$temp[1];
                    $dataInput[$i]['kpi_month']=$month;
                    $dataInput[$i]['kpi_target']=$value;
                    $dataInput[$i]['istatus']=0;
                    $dataInput[$i]['created_by']=$this->session->userdata('username');
                    $i++;
                }
                $this->db->trans_start();
                if($action=="New"){
                    $this->assignNew($dataInput);
                } elseif ($action=="Update") {
                    $this->assignUpdate($dataInput);
                }
                $this->db->trans_complete();
                
                if ($this->db->trans_status() === FALSE) {
                    echo "Transaction Error";
                } 
            }
        } elseif($process=="Update") {
            
        }
        $this->load->view($data['template'],$data);
	}
	
	function assignUpdate($data){
	   $this->mtarget->updateTarget($data);
	}
	
	function assignDelete(){
	
	}
	
	function getUserTarget($user_group="",$month=""){
	   if ($user_group=="" || $month==""){
	       $return['status']='error';
           $return['description']='Incomplete Parameter';
           echo json_encode($return);
           return;
	   }
	   
       $userTarget=$this->mtarget->getUserTarget($user_group,$month);
       echo $userTarget;
	}	
    
    function getTargetAllocation($month=""){
        if ($month==""){
	       $return['status']='error';
           $return['description']='Incomplete Parameter';
           echo json_encode($return);
           return;
	   }
	   
       $targetAllocation=$this->mtarget->getTargetAllocation($month,8);
       echo $targetAllocation;
    }
}
 